<template>
  <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      title="重置用户密码"
      @ok="handleSubmit"
      @cancel="handelCancel"
  >
    <BasicForm
        :labelWidth="100"
        :schemas="schemas"
        ref="formElRef"
        :showResetButton="false"
        :showSubmitButton="false"
        :actionColOptions="{ span: 24 }"
    />
    <template #footer>
      <a-button key="back" @click="handelCancel">
        取消
      </a-button>
      <a-button key="submit" type="primary" @click="handleSubmit">
        重置密码
      </a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
import {BasicModal, useModalInner} from '@/components/Modal';
import {BasicForm, FormActionType, FormSchema} from '@/components/Form';
import {ref} from 'vue';
import {useMessage} from "@/hooks/web/useMessage";
import {updatePwdApi} from "@/api/sys/user";
import {UpdatePwdParams} from "@/api/sys/model/userModel";
import {useUserStore} from "@/store/modules/user";
import { useAppInject } from "@/hooks/web/useAppInject";

const {createMessage} = useMessage();
const { getIsMobile } = useAppInject();
const userStore = useUserStore();
const formElRef = ref<FormActionType>(null as FormActionType);
const schemas: FormSchema[] = [
  {
    field: 'oldPwd',
    component: 'InputPassword',
    label: '原密码',
    colProps: {
      span: 24,
    },
    componentProps: {
      placeholder: '请输入原密码',
    },
    rules: [{required: true}],

  },
  {
    field: 'newPwd1',
    component: 'InputPassword',
    label: '新密码',
    colProps: {
      span: 24,
    },
    componentProps: {
      placeholder: '请输入新密码',
    },
    rules: [{required: true}],

  },
  {
    field: 'newPwd2',
    component: 'InputPassword',
    label: '新密码',
    colProps: {
      span: 24,
    },
    componentProps: {
      placeholder: '请再次输入新密码',
    },
    rules: [{required: true}],
  },
];

const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  setModalProps({
    confirmLoading: false,
    cancelText: '关闭',
    defaultFullscreen: getIsMobile.value,
  });
});

function handelCancel() {
  formElRef.value.resetFields();
  closeModal();
}

function handleSubmit() {
  formElRef.value.validate().then(async (values) => {
    var fieldsValue = formElRef.value.getFieldsValue();
    // 如果 newPwd1 和 newPwd2 不一致
    if (fieldsValue.newPwd1 !== fieldsValue.newPwd2) {
      createMessage.error('两次输入的新密码不一致');
      return;
    }
    // 如果新旧密码一直
    if (fieldsValue.oldPwd === fieldsValue.newPwd1) {
      createMessage.error('新密码不能与旧密码一致');
      return;
    }
    updatePwdApi({
      oldPwd: fieldsValue.oldPwd,
      newPwd1: fieldsValue.newPwd1,
      newPwd2: fieldsValue.newPwd2,
    } as UpdatePwdParams).then(
        (res) => {
          createMessage.success('重置密码成功');
          closeModal();
          userStore.logout(true);
        }
    )
    await formElRef.value.resetFields();
  });
}
</script>
